package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private final StringRedisTemplate stringRedisTemplate;

    // 锁(键)的格式：KEY_PREFIX  + name
    private static final String KEY_PREFIX = "lock:";  // 锁(键)的前缀
    private final String name;  // 锁(键)的名称

    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";  // 值的前缀

    // 释放锁的脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.MINUTES);
        return Boolean.TRUE.equals(isLock);   // isLock为true时返回true，为false时返回false，为空时也返回false
    }

    @Override
    public void unLock() {
        /*// 当前线程的锁的值
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // redis中的锁的值
        String value = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 两者一致，删除锁
        if(threadId.equals(value))
            stringRedisTemplate.delete(KEY_PREFIX + name);*/

        // 使用lua脚本，保证原子性
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),          // KEYS[1]
                ID_PREFIX + Thread.currentThread().getId()   // ARGV[1]
        );
    }
}

